package com.ming.study.common.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author mingminghu
 */
public class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false)
            .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);

    /**
     * Serialize object to json string
     *
     * @param obj object instance
     * @return json string
     */
    public static String toJson(Object obj) throws JsonProcessingException {
        if (obj == null) {
            return StringUtils.EMPTY;
        }
        return OBJECT_MAPPER.writeValueAsString(obj);
    }


    /**
     * Deserialization json string to specified type object
     *
     * @param json  json string
     * @param <T>   type param
     * @return type <T> instance
     */
    public static <T> T fromJson(String json, Class<T> clazz)
            throws IOException, JsonParseException, JsonMappingException {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        return OBJECT_MAPPER.readValue(json, clazz);
    }

    /**
     * Deserialization json array to specified type object list
     *
     * @param jsonArray  josn array
     */
    public static <T> List<T> jsonArray2list(String jsonArray, Class<T> clazz) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JavaType t = mapper.getTypeFactory().constructParametricType(List.class, clazz);
        return mapper.readValue(jsonArray, t);
    }
}
